package org.example.ssmDemo.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import javax.annotation.Resource;
import org.apache.logging.log4j.util.Strings;
import org.example.ssmDemo.entity.DoctorEntity;
import org.example.ssmDemo.entity.DoctorHaoEntity;
import org.example.ssmDemo.mapper.DoctorInfoMapper;
import org.example.ssmDemo.task.DoctorDealAction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @author cliang.liangchao
 * @version 1.0
 * @Description:
 * @date: 2021/11/22
 */
@Service
public class DoctorInfoService {

    private final static Logger LOGGER = LoggerFactory.getLogger(DoctorInfoService.class);

    private int processPerCount = 100;

    @Resource
    private DoctorInfoMapper doctorInfoMapper;

    /**
     * 根据药物ID获取相关的各类进度
     */
    public void refreshDoctorInfo() {
        // 开始加载所有医生信息到内存中
        LOGGER.info("开始遍历加载医生信息到内存中...");
        long total = getDoctorCount();
        LOGGER.info("{} doctor data need to be processed, ", total);

        for (int pageNo = 0; pageNo * processPerCount < total; pageNo++) {
            List<DoctorEntity> doctorEntityList = getDoctorList(pageNo * processPerCount, processPerCount);
            LOGGER.info("The task is dealing with data no.{} to no.{}", (pageNo * processPerCount) + 1,
                    (pageNo + 1) * processPerCount);

            // 创建包含Runtime.getRuntime().availableProcessors()返回值作为个数的并行线程的ForkJoinPool
            ForkJoinPool forkJoinPool = new ForkJoinPool();
            forkJoinPool.invoke(new DoctorDealAction(doctorEntityList, this, 0, doctorEntityList.size()));
            // 关闭线程池
            forkJoinPool.shutdown();
        }

    }

    /**
     * 获取医生总数
     *
     * @return 医生总数
     */
    private long getDoctorCount() {
        return doctorInfoMapper.getDoctorCount();
    }

    private List<DoctorEntity> getDoctorList(int pageNo, int pageSize) {
        return doctorInfoMapper.getDoctorList(pageNo, pageSize);
    }

    /**
     * 查询医院别名
     *
     * @param hospName 医院标准名
     * @return 别名列表
     */
    public List<String> queryHospAlias(String hospName) {
        return doctorInfoMapper.queryHospAlias(hospName);
    }

    /**
     * 用医院名、医生名匹配好大夫表中的医生
     *
     * @param doctorName 医生名
     * @param hospName 医院标准名
     * @param aliasList 别名列表
     * @return 匹配的医生列表
     */
    public List<DoctorHaoEntity> queryDoctorInHaoDaiFu(String doctorName, String hospName, List<String> aliasList) {
        return doctorInfoMapper.queryDoctorInHaoDaiFu(doctorName, hospName, aliasList);
    }

    /**
     * 医生实体信息
     * @param doctorEntity 医生实体
     */
    public void updateClinicalTile(DoctorEntity doctorEntity) {
        doctorInfoMapper.updateClinicalTile(doctorEntity);
    }
}
